import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/widget/clx_web_widget.dart';

class WebController extends GetxController {
  WebController();

  late String url; // web url
  double loadPercentage = 0; //网页加载百分比
  final WebViewController webViewController =
      WebViewController(); // 网页controller

  _initData() {
    update(["web"]);
  }

  void initWeb() {
    webViewController
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setOnConsoleMessage((message) {
        loggerNoStack.w(message.message);
      })
      ..addJavaScriptChannel("callFlutterAction",
          onMessageReceived: (JavaScriptMessage message) async {
        logger.d(
            "JavascriptChannel:method = callFlutterAction message = ${message.message}");
        // _honMessageReceived(message.message);
      })
      ..setNavigationDelegate(NavigationDelegate(
        onPageFinished: onPageFinished,
        onPageStarted: onPageStarted,
        onProgress: onProgress,
      ))
      ..loadRequest(
          Uri.parse(url));
  }

  /// 返回
  Future<bool> onBack() async {
    try {
      // canGoBack()会出现空指针
      if (await webViewController.canGoBack() == true) {
        webViewController.goBack();
        return Future.value(false);
      }
      Get.back();
    } catch (e) {
      Get.back();
    }
    return Future.value(false);
  }

  /// 网页开始加载
  void onPageStarted(String url) {
    logger.d("web onPageStarted：url = $url");
  }

  /// 网页加载完成
  void onPageFinished(String url) async {
    logger.d("web onPageFinished：url = $url");
  }

  /// 网页加载中
  onProgress(int progress) async {
    loadPercentage = progress / 100;
    if (loadPercentage >= 1) {}
    _initData();
  }

  @override
  void onInit() {
    Map? map = Get.arguments;
    url = map?["url"];
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    initWeb();
  }

  @override
  void onClose() {
    webViewController.clearCache();
    super.onClose();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
